import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jiang Jining
 * @since 2021/11/28 23:18
 */
public class Solution697 {
    public int findShortestSubArray(int[] nums) {
        List<Integer> fitNums = new ArrayList<>();
        int time = 0;
        
        Map<Integer, int[]> times = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int[] newTime = times.getOrDefault(nums[i], new int[]{0, -1, -1});
            ++newTime[0];
            if (newTime[1] == -1) {
                newTime[1] = i;
            }
            
            newTime[2] = i;
            times.put(nums[i], newTime);
            if (newTime[0] < time) {
                continue;
            }
            
            if (newTime[0] > time) {
                fitNums.clear();
            }
            
            time = newTime[0];
            fitNums.add(nums[i]);
        }
        
        int res = nums.length;
        for (int num : fitNums) {
            int[] nowTime = times.get(num);
            res = Math.min(nowTime[2] - nowTime[1] + 1, res);
        }
        return res;
    }
}
